<template>
  <div class="role-list-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRole" v-if="checkPermission('sys:role:add')">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" v-if="checkPermission('sys:role:delete')" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" layout="inline" size="small" @submit.prevent>
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input
            v-model="searchForm.roleCode"
            placeholder="请输入角色编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色列表表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="roleList"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="角色ID" width="120" />
        <el-table-column prop="name" label="角色名称" width="180" />
        <el-table-column prop="code" label="角色编码" width="180" />
        <el-table-column prop="description" label="角色描述" show-overflow-tooltip>
          <template #default="scope">
            <el-popover
              trigger="hover"
              placement="top"
              width="300"
            >
              <p>{{ scope.row.description || '暂无描述' }}</p>
              <template #reference>
                <span>{{ scope.row.description || '暂无描述' }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
              v-if="checkPermission('sys:role:edit')"
              :disabled="scope.row.code === 'ADMIN'"
            />
            <span v-else>{{ scope.row.status === 1 ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(scope.row)"
              v-if="checkPermission('sys:role:edit')"
              :disabled="scope.row.code === 'ADMIN'"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteRole(scope.row.id)"
              v-if="checkPermission('sys:role:delete')"
              :disabled="scope.row.code === 'ADMIN'"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleAssignPermissions(scope.row)"
              v-if="checkPermission('sys:role:assignPermission')"
            >
              <el-icon><Key /></el-icon>
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        class="role-form"
      >
        <el-form-item prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            clearable
            :disabled="roleForm.code === 'ADMIN'"
          />
        </el-form-item>
        <el-form-item prop="code" v-if="!roleForm.id">
          <el-input
            v-model="roleForm.code"
            placeholder="请输入角色编码（大写字母+下划线）"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色编码" v-if="roleForm.id">
          <el-input
            v-model="roleForm.code"
            disabled
          />
        </el-form-item>
        <el-form-item prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item prop="status">
          <el-switch
            v-model="roleForm.status"
            active-value="1"
            inactive-value="0"
            :disabled="roleForm.code === 'ADMIN'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
      top="10vh"
    >
      <el-form :model="assignPermissionForm">
        <el-form-item label="当前角色">
          <el-input v-model="assignPermissionForm.roleName" disabled />
        </el-form-item>
        <el-form-item label="权限列表">
          <div class="permission-tree-container">
            <el-tree
              ref="permissionTree"
              :data="permissionList"
              :props="permissionTreeProps"
              node-key="id"
              show-checkbox
              default-expand-all
              :default-checked-keys="assignPermissionForm.permissionIds"
              @check-change="handlePermissionCheckChange"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'RoleList',
  setup() {
    // 表格数据和加载状态
    const roleList = ref([])
    const loading = ref(false)
    const selectedRows = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      roleName: '',
      roleCode: '',
      status: ''
    })
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const permissionDialogVisible = ref(false)
    const dialogTitle = ref('')
    
    // 角色表单
    const roleFormRef = ref(null)
    const roleForm = reactive({
      id: '',
      name: '',
      code: '',
      description: '',
      status: 1
    })
    
    // 角色表单验证规则
    const roleRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 30, message: '角色名称长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },
        { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
      ]
    }
    
    // 权限数据
    const permissionList = ref([])
    const permissionTree = ref(null)
    const permissionTreeProps = {
      label: 'name',
      children: 'children'
    }
    
    const assignPermissionForm = reactive({
      roleId: '',
      roleName: '',
      permissionIds: []
    })
    
    // 加载角色列表
    const loadRoleList = async () => {
      try {
        loading.value = true
        
        // 这里应该调用后端API获取真实数据
        // 由于是模拟环境，我们使用mock数据
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // Mock角色数据
        const mockData = [
          {
            id: 1,
            name: '系统管理员',
            code: 'ADMIN',
            description: '系统管理员，拥有所有权限',
            status: 1,
            createTime: '2025-09-01 10:20:30',
            updateTime: '2025-09-10 15:30:45'
          },
          {
            id: 2,
            name: '普通用户',
            code: 'USER',
            description: '普通用户，拥有基础操作权限',
            status: 1,
            createTime: '2025-09-02 09:15:20',
            updateTime: '2025-09-05 14:25:10'
          },
          {
            id: 3,
            name: '只读用户',
            code: 'READONLY',
            description: '只读用户，只能查看数据，不能修改',
            status: 1,
            createTime: '2025-09-03 11:30:45',
            updateTime: '2025-09-08 16:40:25'
          },
          {
            id: 4,
            name: '内容审核员',
            code: 'CONTENT_AUDITOR',
            description: '内容审核员，负责审核系统内容',
            status: 1,
            createTime: '2025-09-04 13:25:15',
            updateTime: '2025-09-09 10:15:30'
          },
          {
            id: 5,
            name: '财务人员',
            code: 'FINANCE',
            description: '财务人员，负责财务相关操作',
            status: 1,
            createTime: '2025-09-05 15:40:30',
            updateTime: '2025-09-10 09:25:45'
          }
        ]
        
        // 模拟分页
        const startIndex = (pagination.currentPage - 1) * pagination.pageSize
        const endIndex = startIndex + pagination.pageSize
        roleList.value = mockData.slice(startIndex, endIndex)
        pagination.total = mockData.length
        
      } catch (error) {
        console.error('加载角色列表失败:', error)
        ElMessage.error('加载角色列表失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 加载权限列表
    const loadPermissionList = async () => {
      try {
        // Mock权限数据，构建树形结构
        permissionList.value = [
          {
            id: 1,
            name: '系统管理',
            code: 'sys:manage',
            children: [
              {
                id: 2,
                name: '用户管理',
                code: 'sys:user:manage',
                children: [
                  { id: 3, name: '查询用户', code: 'sys:user:query' },
                  { id: 4, name: '新增用户', code: 'sys:user:add' },
                  { id: 5, name: '编辑用户', code: 'sys:user:edit' },
                  { id: 6, name: '删除用户', code: 'sys:user:delete' },
                  { id: 7, name: '分配角色', code: 'sys:user:assignRole' }
                ]
              },
              {
                id: 8,
                name: '角色管理',
                code: 'sys:role:manage',
                children: [
                  { id: 9, name: '查询角色', code: 'sys:role:query' },
                  { id: 10, name: '新增角色', code: 'sys:role:add' },
                  { id: 11, name: '编辑角色', code: 'sys:role:edit' },
                  { id: 12, name: '删除角色', code: 'sys:role:delete' },
                  { id: 13, name: '分配权限', code: 'sys:role:assignPermission' }
                ]
              },
              {
                id: 14,
                name: '权限管理',
                code: 'sys:permission:manage',
                children: [
                  { id: 15, name: '查询权限', code: 'sys:permission:query' },
                  { id: 16, name: '新增权限', code: 'sys:permission:add' },
                  { id: 17, name: '编辑权限', code: 'sys:permission:edit' },
                  { id: 18, name: '删除权限', code: 'sys:permission:delete' }
                ]
              }
            ]
          },
          {
            id: 19,
            name: '审计日志',
            code: 'audit:manage',
            children: [
              { id: 20, name: '查询日志', code: 'audit:query' },
              { id: 21, name: '导出日志', code: 'audit:export' }
            ]
          }
        ]
      } catch (error) {
        console.error('加载权限列表失败:', error)
        ElMessage.error('加载权限列表失败')
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      loadRoleList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      loadRoleList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadRoleList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      loadRoleList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (rows) => {
      selectedRows.value = rows
    }
    
    // 处理状态变化
    const handleStatusChange = async (row) => {
      try {
        if (row.code === 'ADMIN') {
          row.status = 1
          ElMessage.warning('管理员角色状态不能修改')
          return
        }
        
        // 这里应该调用后端API更新角色状态
        
        ElMessage.success('状态更新成功')
      } catch (error) {
        console.error('更新状态失败:', error)
        // 失败时回滚状态
        row.status = row.status === 1 ? 0 : 1
        ElMessage.error('更新状态失败，请稍后重试')
      }
    }
    
    // 处理新增角色
    const handleAddRole = () => {
      dialogTitle.value = '新增角色'
      // 重置表单
      Object.keys(roleForm).forEach(key => {
        roleForm[key] = ''
      })
      roleForm.status = 1
      dialogVisible.value = true
    }
    
    // 处理编辑角色
    const handleEditRole = (row) => {
      dialogTitle.value = '编辑角色'
      // 复制角色数据到表单
      Object.assign(roleForm, { ...row })
      dialogVisible.value = true
    }
    
    // 处理保存角色
    const handleSaveRole = async () => {
      try {
        if (roleForm.code === 'ADMIN') {
          ElMessage.warning('管理员角色不能修改')
          return
        }
        
        await roleFormRef.value.validate()
        
        // 这里应该调用后端API保存角色
        
        if (roleForm.id) {
          // 编辑角色
          ElMessage.success('角色编辑成功')
        } else {
          // 新增角色
          ElMessage.success('角色新增成功')
        }
        
        // 关闭对话框并刷新列表
        dialogVisible.value = false
        loadRoleList()
      } catch (error) {
        console.error('保存角色失败:', error)
        ElMessage.error('保存角色失败，请稍后重试')
      }
    }
    
    // 处理删除角色
    const handleDeleteRole = async (id) => {
      try {
        const role = roleList.value.find(item => item.id === id)
        if (role && role.code === 'ADMIN') {
          ElMessage.warning('管理员角色不能删除')
          return
        }
        
        await ElMessageBox.confirm(
          '确定要删除该角色吗？此操作将影响所有拥有该角色的用户。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API删除角色
        
        ElMessage.success('角色删除成功')
        loadRoleList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除角色失败:', error)
          ElMessage.error('删除角色失败，请稍后重试')
        }
      }
    }
    
    // 处理批量删除
    const handleBatchDelete = async () => {
      try {
        if (selectedRows.value.length === 0) {
          ElMessage.warning('请先选择要删除的角色')
          return
        }
        
        // 检查是否包含管理员角色
        const hasAdminRole = selectedRows.value.some(row => row.code === 'ADMIN')
        if (hasAdminRole) {
          ElMessage.warning('选中的角色包含管理员角色，无法批量删除')
          return
        }
        
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedRows.value.length} 个角色吗？此操作将影响所有拥有这些角色的用户。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API批量删除角色
        
        ElMessage.success('角色批量删除成功')
        selectedRows.value = []
        loadRoleList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除角色失败:', error)
          ElMessage.error('批量删除角色失败，请稍后重试')
        }
      }
    }
    
    // 处理分配权限
    const handleAssignPermissions = (row) => {
      assignPermissionForm.roleId = row.id
      assignPermissionForm.roleName = row.name
      // 这里应该调用后端API获取角色已分配的权限
      // 模拟数据
      assignPermissionForm.permissionIds = row.id === 1 
        ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] 
        : [3, 9, 15, 20]
      permissionDialogVisible.value = true
      loadPermissionList()
    }
    
    // 处理权限选择变化
    const handlePermissionCheckChange = () => {
      // 当权限选择变化时，更新选中的权限ID列表
      if (permissionTree.value) {
        assignPermissionForm.permissionIds = permissionTree.value.getCheckedKeys()
      }
    }
    
    // 处理保存权限分配
    const handleSavePermissions = async () => {
      try {
        // 这里应该调用后端API保存权限分配
        
        ElMessage.success('权限分配成功')
        permissionDialogVisible.value = false
      } catch (error) {
        console.error('保存权限分配失败:', error)
        ElMessage.error('保存权限分配失败，请稍后重试')
      }
    }
    
    // 处理对话框关闭
    const handleDialogClose = () => {
      if (roleFormRef.value) {
        roleFormRef.value.resetFields()
      }
    }
    
    // 检查权限
    const checkPermission = (permissionCode) => {
      // 从localStorage获取用户权限
      const permissions = JSON.parse(localStorage.getItem('permissions') || '[]')
      // 检查是否包含所需权限
      return permissions.includes(permissionCode)
    }
    
    onMounted(() => {
      loadRoleList()
    })
    
    return {
      roleList,
      loading,
      selectedRows,
      searchForm,
      pagination,
      dialogVisible,
      permissionDialogVisible,
      dialogTitle,
      roleFormRef,
      roleForm,
      roleRules,
      permissionList,
      permissionTree,
      permissionTreeProps,
      assignPermissionForm,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleStatusChange,
      handleAddRole,
      handleEditRole,
      handleSaveRole,
      handleDeleteRole,
      handleBatchDelete,
      handleAssignPermissions,
      handlePermissionCheckChange,
      handleSavePermissions,
      handleDialogClose,
      checkPermission
    }
  }
}
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-form {
  max-height: 400px;
  overflow-y: auto;
}

.permission-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .el-form--inline .el-form-item {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .el-form--inline .el-input {
    width: 100% !important;
  }
}
</style>